<template>
  <div class="review-container">
    <div class="review-header">
      <h2>新闻审核管理</h2>
      <p class="subtitle">审核待发布的新闻内容</p>
    </div>

    <div class="review-content">
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-select v-model="filterStatus" placeholder="审核状态" clearable @change="handleFilter">
              <el-option label="待审核" value="pending" />
              <el-option label="已通过" value="approved" />
              <el-option label="已拒绝" value="rejected" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="filterCategory" placeholder="新闻分类" clearable @change="handleFilter">
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索标题或作者"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="refreshData">刷新</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 新闻列表 -->
      <div class="news-list">
        <el-table
          :data="newsList"
          v-loading="loading"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="封面" width="120">
            <template #default="scope">
              <img
                v-if="scope.row.picPath"
                :src="scope.row.picPath"
                class="news-cover"
                @click="previewImage(scope.row.picPath)"
              />
              <div v-else class="no-image">无图片</div>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" min-width="200">
            <template #default="scope">
              <div class="news-title" @click="previewNews(scope.row)">
                {{ scope.row.title }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="author" label="作者" width="100" />
          <el-table-column label="分类" width="100">
            <template #default="scope">
              {{ getCategoryName(scope.row.categoryId) }}
            </template>
          </el-table-column>
          <el-table-column prop="createDate" label="提交时间" width="160">
            <template #default="scope">
              {{ formatDate(scope.row.createDate) }}
            </template>
          </el-table-column>
          <el-table-column label="审核状态" width="100">
            <template #default="scope">
              <el-tag
                :type="getStatusType(scope.row.reviewStatus)"
                size="small"
              >
                {{ getStatusText(scope.row.reviewStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                v-if="scope.row.reviewStatus === 'pending'"
                type="success"
                size="small"
                @click="handleApprove(scope.row)"
              >
                通过
              </el-button>
              <el-button
                v-if="scope.row.reviewStatus === 'pending'"
                type="danger"
                size="small"
                @click="handleReject(scope.row)"
              >
                拒绝
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="previewNews(scope.row)"
              >
                预览
              </el-button>
              <el-button
                v-if="scope.row.reviewStatus !== 'pending'"
                type="info"
                size="small"
                @click="viewReviewDetail(scope.row)"
              >
                审核详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedNews.length > 0">
      <el-button type="success" @click="batchApprove">批量通过</el-button>
      <el-button type="danger" @click="batchReject">批量拒绝</el-button>
    </div>

    <!-- 新闻预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="新闻预览"
      width="80%"
      class="preview-dialog"
    >
      <div class="preview-content" v-if="previewData">
        <h1>{{ previewData.title }}</h1>
        <div class="preview-meta">
          <span>分类：{{ getCategoryName(previewData.categoryId) }}</span>
          <span>作者：{{ previewData.author }}</span>
          <span>提交时间：{{ formatDate(previewData.createDate) }}</span>
        </div>
        <img v-if="previewData.picPath" :src="previewData.picPath" class="preview-image" />
        <div class="preview-summary" v-if="previewData.summary">
          <h3>摘要</h3>
          <p>{{ previewData.summary }}</p>
        </div>
        <div class="preview-body" v-html="previewData.content"></div>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      :title="reviewDialogTitle"
      width="500px"
    >
      <el-form :model="reviewForm" label-width="80px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="reviewForm.reviewStatus">
            <el-radio label="approved">通过</el-radio>
            <el-radio label="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input
            v-model="reviewForm.reviewComments"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview" :loading="reviewing">
            {{ reviewing ? '提交中...' : '提交审核' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="审核详情"
      width="600px"
    >
      <div class="review-detail" v-if="reviewDetail">
        <div class="detail-item">
          <label>审核状态：</label>
          <el-tag :type="getStatusType(reviewDetail.reviewStatus)">
            {{ getStatusText(reviewDetail.reviewStatus) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <label>审核时间：</label>
          <span>{{ formatDate(reviewDetail.reviewTime) }}</span>
        </div>
        <div class="detail-item">
          <label>审核人员：</label>
          <span>{{ reviewDetail.reviewerName || '系统' }}</span>
        </div>
        <div class="detail-item" v-if="reviewDetail.reviewComments">
          <label>审核意见：</label>
          <p class="review-comments">{{ reviewDetail.reviewComments }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="imagePreviewVisible"
      title="图片预览"
      width="600px"
      center
    >
      <img v-if="previewImageUrl" :src="previewImageUrl" class="preview-full-image" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

// 响应式数据
const loading = ref(false)
const newsList = ref([])
const categories = ref([])
const selectedNews = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 筛选条件
const filterStatus = ref('')
const filterCategory = ref('')
const searchKeyword = ref('')

// 对话框控制
const previewVisible = ref(false)
const previewData = ref(null)
const reviewDialogVisible = ref(false)
const reviewDialogTitle = ref('')
const detailDialogVisible = ref(false)
const imagePreviewVisible = ref(false)
const previewImageUrl = ref('')

// 审核相关
const reviewing = ref(false)
const currentReviewNews = ref(null)
const reviewDetail = ref(null)

// 审核表单
const reviewForm = reactive({
  reviewStatus: 'approved',
  reviewComments: ''
})

// 获取新闻列表
const fetchNewsList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      status: filterStatus.value,
      categoryId: filterCategory.value,
      keyword: searchKeyword.value
    }
    
    const response = await axios.get('/app/news/review/list', { params })
    
    if (response.data.code === 200) {
      newsList.value = response.data.data.records
      total.value = response.data.data.total
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取新闻列表失败:', error)
    ElMessage.error('获取数据失败，请重试')
  } finally {
    loading.value = false
  }
}

// 获取分类数据
const fetchCategories = async () => {
  try {
    const response = await axios.get('/app/categories')
    if (response.data.code === 200) {
      categories.value = response.data.data
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 筛选和搜索
const handleFilter = () => {
  currentPage.value = 1
  fetchNewsList()
}

const handleSearch = () => {
  currentPage.value = 1
  fetchNewsList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchNewsList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchNewsList()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedNews.value = selection
}

// 刷新数据
const refreshData = () => {
  fetchNewsList()
}

// 工具函数
const getCategoryName = (id) => {
  const category = categories.value.find(c => c.id === id)
  return category ? category.name : '未分类'
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || '未知'
}

// 预览功能
const previewNews = (news) => {
  previewData.value = news
  previewVisible.value = true
}

const previewImage = (url) => {
  previewImageUrl.value = url
  imagePreviewVisible.value = true
}

// 审核功能
const handleApprove = (news) => {
  currentReviewNews.value = news
  reviewForm.reviewStatus = 'approved'
  reviewForm.reviewComments = ''
  reviewDialogTitle.value = `审核通过 - ${news.title}`
  reviewDialogVisible.value = true
}

const handleReject = (news) => {
  currentReviewNews.value = news
  reviewForm.reviewStatus = 'rejected'
  reviewForm.reviewComments = ''
  reviewDialogTitle.value = `审核拒绝 - ${news.title}`
  reviewDialogVisible.value = true
}

const submitReview = async () => {
  if (!reviewForm.reviewComments.trim()) {
    ElMessage.warning('请输入审核意见')
    return
  }

  reviewing.value = true
  try {
    const reviewData = {
      contentId: currentReviewNews.value.id,
      reviewerId: localStorage.getItem('userId'), // 从用户信息获取
      reviewStatus: reviewForm.reviewStatus,
      reviewComments: reviewForm.reviewComments
    }
    
    const response = await axios.post('/app/news/review', reviewData)
    
    if (response.data.code === 200) {
      ElMessage.success('审核提交成功')
      reviewDialogVisible.value = false
      fetchNewsList()
    } else {
      ElMessage.error(response.data.message || '审核失败')
    }
  } catch (error) {
    console.error('审核失败:', error)
    ElMessage.error('审核失败，请重试')
  } finally {
    reviewing.value = false
  }
}

// 查看审核详情
const viewReviewDetail = async (news) => {
  try {
    const response = await axios.get(`/app/news/review/detail/${news.id}`)
    if (response.data.code === 200) {
      reviewDetail.value = response.data.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error('获取审核详情失败')
    }
  } catch (error) {
    console.error('获取审核详情失败:', error)
    ElMessage.error('获取审核详情失败')
  }
}

// 批量操作
const batchApprove = async () => {
  if (selectedNews.value.length === 0) {
    ElMessage.warning('请选择要审核的新闻')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要通过选中的 ${selectedNews.value.length} 条新闻吗？`,
      '批量审核',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return
  }

  const promises = selectedNews.value.map(news => {
    const reviewData = {
      contentId: news.id,
      reviewerId: localStorage.getItem('userId'),
      reviewStatus: 'approved',
      reviewComments: '批量审核通过'
    }
    return axios.post('/app/news/review', reviewData)
  })

  try {
    await Promise.all(promises)
    ElMessage.success('批量审核成功')
    fetchNewsList()
  } catch (error) {
    console.error('批量审核失败:', error)
    ElMessage.error('批量审核失败')
  }
}

const batchReject = async () => {
  if (selectedNews.value.length === 0) {
    ElMessage.warning('请选择要审核的新闻')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要拒绝选中的 ${selectedNews.value.length} 条新闻吗？`,
      '批量审核',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return
  }

  const promises = selectedNews.value.map(news => {
    const reviewData = {
      contentId: news.id,
      reviewerId: localStorage.getItem('userId'),
      reviewStatus: 'rejected',
      reviewComments: '批量审核拒绝'
    }
    return axios.post('/app/news/review', reviewData)
  })

  try {
    await Promise.all(promises)
    ElMessage.success('批量审核成功')
    fetchNewsList()
  } catch (error) {
    console.error('批量审核失败:', error)
    ElMessage.error('批量审核失败')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategories()
  fetchNewsList()
})
</script>

<style scoped>
.review-container {
  max-width: 1400px;
  margin: 20px auto;
  padding: 20px;
}

.review-header {
  text-align: center;
  margin-bottom: 30px;
}

.review-header h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.subtitle {
  color: #666;
  font-size: 16px;
}

.review-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.filter-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.news-list {
  margin-bottom: 20px;
}

.news-cover {
  width: 80px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s;
}

.news-cover:hover {
  transform: scale(1.05);
}

.no-image {
  width: 80px;
  height: 60px;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
  border-radius: 4px;
}

.news-title {
  color: #409eff;
  cursor: pointer;
  font-weight: 500;
}

.news-title:hover {
  text-decoration: underline;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.batch-actions {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
  background: #fff;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 预览对话框样式 */
.preview-dialog :deep(.el-dialog__body) {
  padding: 30px;
}

.preview-content {
  max-width: 800px;
  margin: 0 auto;
}

.preview-content h1 {
  font-size: 28px;
  margin-bottom: 20px;
  text-align: center;
  color: #333;
}

.preview-meta {
  color: #666;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
  font-size: 14px;
}

.preview-image {
  width: 100%;
  max-height: 400px;
  object-fit: cover;
  margin: 20px 0;
  border-radius: 8px;
}

.preview-summary {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  margin: 20px 0;
  border-left: 4px solid #409eff;
}

.preview-summary h3 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
}

.preview-summary p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

.preview-body {
  line-height: 1.8;
  color: #333;
  margin: 20px 0;
}

.preview-full-image {
  width: 100%;
  height: auto;
  border-radius: 8px;
}

/* 审核详情样式 */
.review-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.detail-item label {
  font-weight: 500;
  color: #333;
  min-width: 100px;
  margin-right: 10px;
}

.review-comments {
  margin: 10px 0 0 0;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  color: #666;
  line-height: 1.6;
}
</style> 